package com.wangy.controller;

import com.wangy.bean.User;
import com.wangy.bean.UserRole;
import com.wangy.mapper.UserRoleMapper;
import com.wangy.service.UserRoleService;
import com.wangy.service.UserService;
import com.wangy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * *@Author yyzb
 * *@Date 2024/10/22 16:48
 * *@Version 1.0
 */

@RestController
@RequestMapping("/admin/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    // 1. 获取所有用户信息
    @GetMapping("getAllUsers")
    public Result<List<User>> getAllUsers(){
        List<User> userList = userService.getAllUsers();
        return Result.of(200, "success", userList);
    }

    // 2. 根据用户id获得用户信息
    @GetMapping("getUser/{id}")
    public Result<User> getUserById(@PathVariable Long id){
        User user = userService.getUserById(id);
        return Result.of(200, "success", user);
    }

    // 3. 新增用户
    @PostMapping("addUser")
    public Result<Void> addUser(@RequestBody User user){
        userService.addUser(user);
        return Result.of(200, "success", null);
    }

    // 4. 删除用户
    @DeleteMapping("deleteUser/{id}")
    public Result<Void> deleteById(@PathVariable Long id){
        userService.deleteById(id);
        return Result.of(200, "success", null);

    }
    // 5. 根据用户id获得用户角色id
    @GetMapping("getRoleIdByUserId/{userId}")
    public Result<Long> getRoleIdByUserId(@PathVariable Long userId){
        Long roleId = userRoleService.getRoleIdByUserId(userId);
        return Result.of(200, "success", roleId);
    }


    // 6.为用户分配角色
    @PostMapping("assignRoleToUser")
    public Result<Void> assignRoleToUser(@RequestBody UserRole userRole) {
        // 为用户分配角色
        userRoleService.addUserIdRoleIdRelationship(userRole.getUserId(), userRole.getRoleId());
        return Result.of(200, "success", null);
    }
}
